Line data Source code
1 : #include "HighPowerTimer.hpp"
2 : #include "ITimerExpiredCallback.hpp"
3 :
4 111 : HighPowerTimer::HighPowerTimer(ITimerExpiredCallback& callback, int durationMs)
5 111 : : callback_(callback), duration_(durationMs), active_(false) {}
6 :
7 74 : HighPowerTimer::~HighPowerTimer() {
8 37 : stop();
9 74 : }
10 :
11 12 : void HighPowerTimer::start() {
12 : // 이전 타이머가 자연 만료된 경우 스레드가 아직 join되지 않았을 수 있다.
13 : // 재대입 전에 join해야 std::terminate를 방지할 수 있다.
14 12 : if (timerThread_.joinable()) {
15 1 : timerThread_.join();
16 1 : }
17 12 : active_ = true;
18 12 : timerThread_ = std::thread(&HighPowerTimer::run, this);
19 12 : }
20 :
21 2 : void HighPowerTimer::reset() {
22 2 : stop();
23 2 : start();
24 2 : }
25 :
26 103 : void HighPowerTimer::stop() {
27 : {
28 103 : std::lock_guard<std::mutex> lock(mutex_);
29 103 : active_ = false;
30 103 : }
31 103 : cv_.notify_all();
32 103 : if (timerThread_.joinable()) {
33 11 : timerThread_.join();
34 11 : }
35 103 : }
36 :
37 12 : void HighPowerTimer::run() {
38 12 : std::unique_lock<std::mutex> lock(mutex_);
39 12 : bool timedOut = !cv_.wait_for(lock,
40 12 : std::chrono::milliseconds(duration_),
41 30 : [this] { return !active_.load(); });
42 12 : if (timedOut && active_) {
43 4 : active_ = false;
44 4 : lock.unlock();
45 4 : callback_.onExpired();
46 4 : }
47 12 : }
|